# coding: utf-8

import json
import os
import asyncio

import tornado
import tornado.httpserver
import tornado.web
from tornado import gen
from tornado.web import asynchronous
from tornado.ioloop import IOLoop

import tcp_server 


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render(r"static/main.html")


class ClientsHandler(tornado.web.RequestHandler):
    def get(self):
        client_names = filter(None, [client.name
            for client in self.settings['tcp_server'].clients.values()])
        self.write(json.dumps(list(client_names)))


class MessagesHandler(tornado.web.RequestHandler):

    @gen.coroutine
    def get(self):
        token = self.get_argument('token')
        self.msg_listener = self.settings['tcp_server'].listen(token)
        name, key, value = (
            yield gen.Task(self.msg_listener.get_msg))
        self.write(json.dumps(
            dict(name=name, key=key, value=value)))
    
    def on_connection_close(self):
        print ('connection closed')
        self.settings['tcp_server'].unsubscribe(self.msg_listener)


application = tornado.web.Application([
        (r"/messages/?", MessagesHandler),
        (r"/clients", ClientsHandler),
        (r"/", MainHandler),
    ],
    static_path=os.path.abspath(
        os.path.join(os.path.dirname(__file__), "static")),
    )

def main():
    from tornado.platform.asyncio import AsyncIOMainLoop
    AsyncIOMainLoop().install()
    
    server = tcp_server.MyServer()
    application.settings.update(tcp_server=server)
    loop = asyncio.get_event_loop()
    server.start(loop)
    
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(9999)

    loop.run_forever()
    
if __name__ == '__main__':
    main()